package sri.proiect.search;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.management.Query;

import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.util.Version;

import sri.proiect.models.Hotel;
import sri.proiect.models.SearchType;
import sri.proiect.utils.DBColumn;

public class MultiCriteriaSearchManager extends AbstractSearcher {

	Map<DBColumn, String> searchMap = new LinkedHashMap<DBColumn, String>();
	
	public static MultiCriteriaSearchManager instance;
	
	public static MultiCriteriaSearchManager instance() {
		if (instance == null) {
			instance = new MultiCriteriaSearchManager();
		}
		
		return instance;
	}

	public void addSearchCriterion(DBColumn column, String searchValue) {
		searchMap.put(column, searchValue);
	}
	
	public List<Hotel> search() {
		List<Hotel> searchResult = new ArrayList<Hotel>();
    	if (false == ckeckOrCreateIndex()) {
    		return searchResult;
    	}

		
		//TermQuery booleanQuery = new BooleanQuery();
    	//TermQuery booleanQuery = new TermQuery();
    	//TermQuery term = new TermQuery(new Term(column.getName(), searchValue));
		//booleanQuery.add(term, Occur.MUST);
    	
   String searchString = "";
		
		for (DBColumn column : searchMap.keySet()) {
			String searchValue = searchMap.get(column);
			
			searchString+= "+" + column.getName() + ":" + searchValue + " ";
		}
		QueryParser queryParser = new QueryParser(Version.LUCENE_CURRENT, "fulltext", analyzer);
		try {
			org.apache.lucene.search.Query query = queryParser.parse(searchString);
			searchForHotels(searchResult, query);
		} catch(Exception e) {e.printStackTrace();} 
		
    	BooleanQuery query = new BooleanQuery();
    	for (DBColumn column : searchMap.keySet()) {
			String searchValue = searchMap.get(column);
			TermQuery tw = new TermQuery(new Term(column.getName(), searchValue));
			query.add(tw, Occur.SHOULD);
		}
    	
    	searchForHotels(searchResult, query);
		return searchResult;
		
	}
}
